package com.sky.controller.user;

/**
 * @author dongdong 抖音号：W13883155245
 * @version 1.0
 * @date 2025/10/5
 * @description
 */
import com.sky.result.Result;
import com.sky.utils.QRCodeUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.io.ByteArrayOutputStream;

import com.sky.utils.QrCodeGenerator;

@RestController
@RequestMapping("/wechat")
public class WechatLoginController {

    // 微信开放平台配置（替换为你的实际配置）
    private static final String WECHAT_APPID = "wxbdc5610cc59c1631";
    private static final String REDIRECT_URI = "https://37080d52.r23.cpolar.top/user/user/login";
    // private static final String REDIRECT_URI = "https://dongdong.cloud";

    /**
     * 接口：获取微信登录二维码（返回图片流）
     */
    @GetMapping("/login/qrcode")
    public Result<String> getWechatLoginQrCode() {
        try {
            // 1. 构建微信登录链接
            String encodedRedirectUri = java.net.URLEncoder.encode(REDIRECT_URI, "UTF-8");
            String randomState = "STATE_" + System.currentTimeMillis();
            // 建议将state存入Redis，设置2分钟过期（与二维码有效期一致）
            // redisTemplate.opsForValue().set("wechat_login_state_" + randomState, "pending", 2, TimeUnit.MINUTES);

            String wechatLoginUrl = String.format(
                    "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect",
                    WECHAT_APPID, encodedRedirectUri, randomState
            );

            // 2. 生成二维码并转为字节数组
            BufferedImage qrImage = QrCodeGenerator.generateCustomColorQrCode(
                    wechatLoginUrl, 200, 200, new Color(7, 193, 96), Color.WHITE
            );
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            QrCodeGenerator.bufferedImageToBytes(qrImage);

          /*  // 3. 设置响应头，返回图片流
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG); // 图片类型为PNG
            headers.setContentLength(outputStream.size());


            return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);*/
            QRCodeUtil qrCodeUtil = new QRCodeUtil();

            System.out.println(wechatLoginUrl);

            String img=qrCodeUtil.createQRCode(wechatLoginUrl,200,200);
            return Result.success(img);

        } catch (Exception e) {
            e.printStackTrace();
            /*return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);*/
            return Result.success(e.toString());
        }
    }
}
